<?php
namespace app\logic;

use app\common\corelib\CacheHelper;
use app\common\HttpCurl;
use app\models\Address;
use app\models\Article;
use app\models\Chapter;
use app\models\Course;
use app\models\Favorite;
use app\models\Goods;
use app\models\History;
use app\models\Paper;
use app\models\Tag;
use app\models\User;
use yii\base\Security;
use yii\db\Query;



class UserLogic
{

    public function findByOpenid($open_id){
        return User::find()->where(['open_id'=>$open_id])->asArray()->one();
    }

    public function getByOpenid($open_id, $access_token=null, $refresh_token=null){
        $user = User::findOne(['open_id'=>$open_id]);
        $userinfo = HttpCurl::get("https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$open_id&lang=zh_CN");
        //var_dump($userinfo);exit;
        if($user){
            $user->nick_name = base64_encode($userinfo['nickname']);
            $user->head_img = $userinfo['headimgurl'];
            $user->access_token = $access_token;
            $user->refresh_token = $refresh_token;
            //$user->last_login_time = date('Y-m-d H:i:s');
            $res = $user->save();
            return $user->toArray();
        }else{
            $user = new User();
            $user->open_id = $open_id;
            //$user->nick_name = $nickname = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $userinfo['nickname']);
            $user->nick_name = base64_encode($userinfo['nickname']);
            $user->head_img = $userinfo['headimgurl'];
            $user->access_token = $access_token;
            $user->refresh_token = $refresh_token;
            //var_dump($user);exit;

            //$user->last_login_time = date('Y-m-d H:i:s');
            $res = $user->save();

            //file_put_contents(date("Ymd")."_testtemp2.txt", $res."|".json_encode($user->toArray())." 日期：".date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
            return $user->toArray();
        }
    }

    public function addUserByOpenId($open_id){
        $user = User::findOne(['open_id'=>$open_id]);
        if($user){
            if(!$user->in_time){
                $user->in_time = date('Y-m-d H:i:s');
                $user->save();
            }
        }else{
            $user = new User();
            $user->open_id = $open_id;
            $user->in_time = date('Y-m-d H:i:s');
            $user->save();
        }
    }

    public function updateMyFile($open_id,$mobile,$email){
        $user = User::findOne(['open_id'=>$open_id]);
        $user->mobile = $mobile;
        $user->email = $email;
        $user->save();
    }

    public function addUser($open_id){
        $user = new User();
        $user->open_id = $open_id;
        $user->in_time = date('Y-m-d H:i:s' );
        $user->save();
    }

    public function addShare($open_id){
        $user = User::findOne(['open_id'=>$open_id]);
        $user->share_num += 1;
        $user->save();
    }

    public function getById($user_id){
        return User::findOne($user_id)->toArray();
    }

    public function addStudyHistory($open_id,$type,$id,$state=1){

        $user = User::find()->where(['open_id'=>$open_id])->asArray()->one();
        if($history = History::findOne(['user_id'=>$user['user_id'],'id'=>$id,'type'=>$type])){
            $history->state = $state;
            $history->time = date('Y-m-d H:i:s');
            if($type==1){
                $chapter = Chapter::findOne($id);
                $chapter->play_num += 1;
                $chapter->save();
            }
        }else{
            $history = new History();
            $history->user_id = $user['user_id'];
            $history->id = $id;
            $history->type = $type;
            $history->time = date('Y-m-d H:i:s');
            if($type==0){
                $article = Article::find()->where(['article_id'=>$id])->asArray()->one();
                $history->title = $article['article_title'];
                $history->pic = $article['article_pic'];
                $history->state = 1;
            }elseif ($type==1){
                /*$chapter = Chapter::find()->where(['chapter_id'=>$id])->asArray()->one();
                $history->pic = $chapter['chapter_pic'];
                $history->state = 1;*/
                $chapter = Chapter::findOne($id);
                $history->title = $chapter->chapter_name;
                $history->pic = $chapter->chapter_pic;
                $history->state = 1;
                $history->course_id = $chapter->course_id;
                $chapter->play_num += 1;
                $chapter->save();
            }else{
                $paper = Paper::find()
                    ->select('p.*,c.chapter_name,co.course_name')
                    ->from('{{%paper}} p')
                    ->leftJoin('{{%chapter}} c','c.paper_id=p.paper_id')
                    ->leftJoin('{{%course}} co','co.course_id=c.course_id')
                    ->where(['p.paper_id'=>$id])->asArray()->one();
                if($paper['course_name'].$paper['chapter_name'])
                    $history->title = $paper['course_name'].$paper['chapter_name'];
                else
                    $history->title = $paper['paper_name'];
                $history->pic = $paper['paper_pic'];
                $history->state = 0;
            }
        }
        $history->save();
        return $history->history_id;
    }

    public function updateStudyHistory($history_id){
        $history = History::findOne($history_id);
        $history->state = 1;
        $history->save();
    }

    public function studyHistory($open_id){
        return History::find()->select('h.*')
            ->from('{{%history}} h')
            ->leftJoin('{{%user}} u','u.user_id=h.user_id')
            ->where(['u.open_id'=>$open_id])
            ->orderBy('time desc')
            ->asArray()
            ->all();
    }

    public function login($open_id,$username,$password){
        $user = User::find()->where(['open_id'=>$open_id])->asArray()->one();
        if($user['username']==$username && $user['password']==$password){
            CacheHelper::set('user_id_'.$user['user_id'],$user);
            $token = MD5($user['user_id'] . $user['open_id'] . time());
            CacheHelper::set('user_token_'.$token,$user);
            return $token;
        }else{
            return false;
        }
    }

    /*public function updateLoginTime($open_id){
        $user = User::findOne(['open_id'=>$open_id]);
        $user->last_login_time = date('Y-m-d');
        $user->save();
    }*/

}
